package com.samebuilding.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.samebuilding.dao.PhotoDAO;
import com.samebuilding.domain.Photo;
import com.samebuilding.domain.User;

public class PhotoDAOImpl extends GenericDAOImpl<Photo, Integer> implements
		PhotoDAO {
	private static final String FIND_BY_CATEGORY_CODE = "from Photo p where p.categoryCode=? order by p.order desc";

	@SuppressWarnings("unchecked")
	public List<Photo> getPhotoByCategoryCode(final int categoryCode,
			final int start, final int limit) {
		List<Photo> list = getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session
								.createQuery(FIND_BY_CATEGORY_CODE);
						query.setInteger(0, categoryCode);
						query.setFirstResult(start);
						query.setMaxResults(limit);
						List<Photo> list = query.list();
						return list;
					}
				});
		return list;
	}

	public long getTotalCountyCategoryCode(int categoryId) {
		List list = getHibernateTemplate().findByNamedQuery(
				"queryTotalCountByCategoryCode", new Object[] { categoryId });
		return (Long) list.get(0);
	}
	@SuppressWarnings("unchecked")
	public List<Photo> getTopPhotoByUserNo(final int userNo, final int count) {
		List<Photo> list = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session
								.getNamedQuery("queryTopPhotoByUserNo");
						query.setInteger(0, userNo);
						query.setMaxResults(count);
						return query.list();
					}

				});
		return list;
	}

	public void addViewer(int photoID, User viewer) {
		Photo photo=this.findById(photoID,false);
		photo.getViewers().add(viewer);
		this.saveOrUpdate(photo);
		this.flushSession();
	}

}